#include <stdio.h>
#include <errno.h>
#include <utmp.h>
#include <pwd.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>


#ifndef UTMP_FILE
#  define UTMP_FILE "/etc/utmp"
#endif
#ifndef WTMP_FILE
#   if defined(SYSV) || defined(SYSTYPE_SYSV)
#       define WTMP_FILE "/etc/wtmp"
#   else
#       define WTMP_FILE "/usr/adm/wtmp"
#   endif
#endif

static int AddUt(uid, line)
	int uid;
	char *line;
{
	int fd, tslot= ttyslot();
	struct utmp utmp;
	struct passwd *pw;
	long pos= -1;
	char *host= getenv("DISPLAY");

	/*
	* Record entry in utmp and/or wtmp if possible.
	*/

	pw= getpwuid(uid);

	bzero(&utmp, sizeof(utmp));
	strncpy(utmp.ut_name, pw ? pw->pw_name : "", sizeof(utmp.ut_name));
	strncpy(utmp.ut_line, &line[5], sizeof(utmp.ut_line));
#if defined(SYSV) || defined(SYSTYPE_SYSV)
	utmp.ut_pid= getpid();
	utmp.ut_type= USER_PROCESS;
#endif
	time(&utmp.ut_time);
	if (host)
		strncpy(utmp.ut_host, host, sizeof(utmp.ut_host));

	fd= open(UTMP_FILE, O_WRONLY);
	if (fd >= 0) {
		if (tslot >= 0)
			pos= lseek(fd, (long)(tslot * sizeof(utmp)), SEEK_SET);
		else
			pos= lseek(fd, 0, SEEK_END);
		if (pos >= 0)
			write(fd, &utmp, sizeof(utmp));
		else
			perror("lseek");
		close(fd);
	}

	if ((fd= open(WTMP_FILE, O_WRONLY | O_APPEND)) >= 0) {
		write(fd, &utmp, sizeof(utmp));
		close(fd);
	}
	fprintf(stderr, "pos: %d\n", pos);
	return pos;
}


static void RmUt(line)
	char *line;
{
	struct utmp utmp, *up;
	int fd;

	bzero(&utmp, sizeof (utmp));
		
#if defined(SYSV) || defined(SYSTYPE_SYSV)
	up= getutline(line);
	if (up)
		pututline(&utmp);
#endif

	if ((fd= open(WTMP_FILE, O_WRONLY | O_APPEND)) >= 0) {
		strncpy(utmp.ut_line, &line[5], sizeof(utmp.ut_line));
		time(&utmp.ut_time);
		write(fd, &utmp, sizeof(utmp));
		close(fd);
	}
}


main(argc, argv)
	int argc;
	char *argv[];
{
	int i, uid, gid, mode, g, u;
	char *slavename;

	for (i= 0; i < argc; i++)
		fprintf(stderr, "%s ", argv[i]);
	fprintf(stderr, "\n");

	slavename= argv[1];
	uid= atoi(argv[2]);
	gid= atoi(argv[3]);
	mode= atoi(argv[4]);

	u= getuid();
	g= getgid();

	if (u != uid || g != gid)
		fprintf(stderr, "aha: %d %d %d %d\n", uid, gid, u, g);

	if (chown(slavename, uid, gid) == -1) {
		if (errno != EPERM)
			perror("chown");
	}

	/* set tty protection */
	if (chmod(slavename, mode) == -1) {
		if (errno != EPERM)
			perror("chmod");
	}

	/* AddUt(); */
	exit(0);
}

